﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Basmus.Resources
{
    public class NamespacePathResolver : IPathResolver
    {
        private readonly bool _backslashed;

        private readonly NamespaceMap _namespaceMap;

        public NamespacePathResolver(bool backslashed, NamespaceMap namespaceMap)
        {
            _backslashed = backslashed;
            _namespaceMap = namespaceMap;
        }

        public string Resolve(Type type)
        {
            var typeNamespace = type.Namespace;
            if (typeNamespace == null || _namespaceMap == null)
                return null;
            var key = _namespaceMap
                .RootNamespaces
                .OrderByDescending(x => x.Length)
                .Where(typeNamespace.StartsWith)
                .Select(x => x)
                .FirstOrDefault();
            if (key == null)
                return null;
            var slash = _backslashed ? '\\' : '/';
            var root = _namespaceMap[key].TrimEnd('\\', '/');
            var restPath = typeNamespace.Remove(0, key.Length).Replace('.', slash).TrimStart('\\', '/');
            var path = root + slash + restPath + slash;
            return path;
        }
    }
}